// *******************************************************************************************************
// # リスト検索画面
//   ・地域選択の表示切替
//   ・路線・駅の「すべて表示」ボタン
//   ・クリアー
//   ・賃料
//   ・専有面積
// *******************************************************************************************************
var PageMove;
var ReSearch;
(function(win, doc) {

	/* 地域選択の表示切替
	----------------------------------- */
	function hopeAreaSelect() {
		var $expSelectBtn = $('.hope_area_select dt');
		var $expSelectArea = $('.hope_area_select dd');
		//初期状態
		$expSelectArea.hide();
		//展開
		$expSelectBtn.on('click',function(){
			$(this).toggleClass('active');
			$(this).parent().children().next().toggle();
		});
	}

	/* 路線・駅の「すべて表示」ボタン
	----------------------------------- */
	function hopeStationOpen() {
		var $expSelectBtn = $('.hope_area_select dt');
		var $expStationList = $('.hope_area_select li:nth-child(n+4)'); //4駅以降を指定
		var $expStationBtn = $('.hope_area_select .btn_all');
		//初期状態
		$expStationList.hide();
		//すべて表示ボタンで4駅以降を表示
		$expStationBtn.on('click',function(){
			$(this).hide();
			$expStationList.show();
		});
		//ボックスを一度閉じたら、初期状態に戻す
		$expSelectBtn.on('click',function(){
			$expStationList.hide();
			$expStationBtn.show();
		});
	}

	/* イニシャライズ
	----------------------------------- */
	function init() {
		var $searchBtn = $('#fixedSearchBtn'),
			$copyright = $('#siteCopyright');

		$searchBtn.show();
		$copyright.css('margin-bottom', 70);
	}

	/* クリアー
	----------------------------------- */
	function clearBtn() {
		var $input  = $('.box_expand_search_list input'),
			select = [
				{ id:'tinryo1',  target:$('select[name=tinryo1]'),  val:0 },
				{ id:'tinryo2',  target:$('select[name=tinryo2]'),  val:9999999 },
				//{ id:'tinryo3',  target:$('select[name=tinryo3]'),  val:9999999 },
				{ id:'senyu1', 	 target:$('select[name=senyu1]'), val:1 },
				{ id:'senyu2', 	 target:$('select[name=senyu2]'), val:99999 },
				{ id:'toho1',    target:$('select[name=toho1]'),    val:0 },
				{ id:'jyoho1',   target:$('select[name=jyoho1]'),   val:0 },
				{ id:'built',    target:$('select[name=built]'),   val:0 },
				{ id:'ekitoho',  target:$('select[name=ekitoho]'),   val:0 },
				{ id:'madori1',  target:$('select[name=madori1]'),   val:'' },
				{ id:'madori2',  target:$('select[name=madori2]'),   val:'' }
			];

		$('.btn_clear a').on('click', function(e){
			$input.prop('checked', false);
			for (var i = 0; i < select.length; i++) {
				select[i].target.val(select[i].val);
			};
		});
	}

	/* 賃料
	----------------------------------- */
	function selectTinryo() {
		var $down = $('select[name=tinryo1]'),
			$up   = $('select[name=tinryo2]');

		$down.on('change', function(e){
			check();
		});
		$up.on('change', function(e){
			check();
		});

		function check() {
			setTimeout(function(e){
				var _val1 = parseInt($down.val());
					_val2 = parseInt($up.val());
				if (_val1 > _val2) {
					$down.val(_val2);
					$up.val(_val1);
				};
			}, 1);
		};
	}
	
	/* 間取り
	----------------------------------- */
	function selectMadori() {
		var $target = $('dl.madori'),
			$type = $target.find('.list_btn_type li'),
			$down = $('select[name=madori1]'),
			$up   = $('select[name=madori2]'),
			$room = $('input[name=room_type]'),
			data = {
				single: ['ワンルーム','1K','1DK','1LDK','2K','2DK'],
				double: ['1LDK','2K','2DK','2LDK','3K','3DK','3LDK'],
				family: ['2LDK','3K','3DK','3LDK','4K','4DK','4LDK','5K以上']
			},
			dataEn = {
					single: ['madori10','madori11','madori12','madori14','madori21','madori22'],
					double: ['madori14','madori21','madori22','madori24','madori31','madori32','madori34'],
					family: ['madori24','madori31','madori32','madori34','madori41','madori42','madori44','madori51']
			},
			id = $room.val();

		$type.each(function(i){
			var _id = $(this).attr('class');
			$(this).on('click', function(e){
				id = _id;
				$room.val(id);
				changeType();
			});
		});
		$down.on('change', function(e){
			changeRoom();
		});
		$up.on('change', function(e){
			changeRoom();
		});
		function changeType(){
			if (!id) return;
			$type.each(function(i){
				if ($(this).attr('class') == id) {
					$(this).find('a').addClass('active');
				} else {
					$(this).find('a').removeClass('active');
				};
			});			
			$down.val(dataEn[id][0]);
			$up.val(dataEn[id][dataEn[id].length-1]);
		};
		function changeRoom(){
			setTimeout(function(e){
				var _val1 = $down.val(),
					_val2 = $up.val(),
					_chk1 = 0,
					_chk2 = 0;
				$down.find('option').each(function(i){
					if ($(this).val() == _val1) {
						_chk1 = i;
						return false;
					};
				});
				$up.find('option').each(function(i){
					if ($(this).val() == _val2) {
						_chk2 = i;
						return false;
					};
				});
				if (_chk1 > _chk2) {
					$down.val(_val2);
					$up.val(_val1);
				};
			}, 1);
		};
		changeType();
	};
	
	//保存された条件から取り出し
	function loadMadori(){
		var madori1 = $('#hidMadori1').val();
		var madori2 = $('#hidMadori2').val();
		if(madori1 != undefined){
			$('#madori1').val(madori1);
		}
		if(madori2 != undefined){
			$('#madori2').val(madori2);
		}
		//メゾネット
		var kodawari77checked = ($('input[name=kodawari77]:checked').length > 0 ? true : false);
		if(kodawari77checked){
			$('input[name=kodawari77]').each(function(){
				$(this).prop('checked', true);
			});
		}
		//メゾネット
		var kodawari62checked = ($('input[name=kodawari62]:checked').length > 0 ? true : false);
		if(kodawari62checked){
			$('input[name=kodawari62]').each(function(){
				$(this).prop('checked', true);
			});
		}
		//2階以上
		var kodawari5checked = ($('input[name=kodawari5]:checked').length > 0 ? true : false);
		if(kodawari5checked){
			$('input[name=kodawari5]').each(function(){
				$(this).prop('checked', true);
			});
		}
		
		//よく検索こだわり
		$('#ulKodawari').find('input[name^=kodawari]').each(function(){
			var name = $(this).attr('name');
			if($('input[name=' + name + ']:checked').length > 0){
				$(this).prop('checked', true);
			}
		});
		
		//20150127-連携こだわり
		
		$('input[name=kodawari77],input[name=kodawari62],input[name=kodawari5],input[name^=Rkodawari]').on('click', function(){
			var name = $(this).attr('name');
			var val = $(this).val();
			var checkName = name;
			if(name == 'kodawari77' || name == 'kodawari62' || name == 'kodawari5'){
				checkName = name;
			}
			else if(val.indexOf('kodawari') >= 0){
				checkName = val.split('-')[0];
			}
			if(!$(this).prop('checked')){					
				$('input[name=' + checkName + ']').each(function(){
					$(this).prop('checked', false);
					$(this).parent().removeClass('checked');
				});						
			}
			else{
				$('input[name=' + checkName + ']').each(function(){
					$(this).prop('checked', true);
					$(this).parent().addClass('checked');
				});
			}
		});
		
		//20150127-連携こだわり
	}

	/* 専有面積
	----------------------------------- */
	function selectMenseki() {
		var $down = $('select[name=senyu1]'),
			$up   = $('select[name=senyu2]');

		$down.on('change', function(e){
			check();
		});
		$up.on('change', function(e){
			check();
		});

		function check() {
			setTimeout(function(e){
				var _val1 = parseInt($down.val());
					_val2 = parseInt($up.val());
				if (_val1 > _val2) {
					$down.val(_val2);
					$up.val(_val1);
				};
			}, 1);
		};
	}
	/*
	 * Submitメソッド
	 */
	function submit(action, method, values) {
 	   var form = $('<form/>', {
	        action: action,
	        method: method
	    });
	    $.each(values, function() {
	        form.append($('<input/>', {
	            type: 'hidden',
	            name: this.name,
	            value: this.value
	        }));    
	    });
	    form.appendTo('body').submit();
	}
	function prepareParams(){
		var items=[];
		var typ = $('input[name="search_type"]').attr("value");
		items.push({name:'search_type',value:typ});

		//市区町村か、路線駅
		$('.search_target').each(function(index){
			items.push({name:'target_'+index,
				    value:$(this).attr("id")});
		});
		
		//町名検索
		$('li[name=search_targetChou]').each(function(index){
			items.push({name:'targetchou_'+index, value:$(this).attr("id")});			
		});
		
		//Dropdown
		$('select').each(function(index){
			var elem = $(this);
			if(elem.attr("id") != 'madori1' && elem.attr("id") != 'madori2'){				
				items.push({name:elem.attr("name"),
					    value:elem.find("option:selected").attr("value"),});
			}
		});
		
		$('li[name=mod_check]').find('input:checked').each(function(index){
//			var elem = $(this);
//			if(!items.hasOwnProperty(elem)){
//				items.push({name:elem.attr("name"), value:elem.attr("value"),});
//			}		
			
			var elem = $(this);
			var val = elem.attr("value");
			
			if(!items.hasOwnProperty(elem)){
				//よく利用こだわりじゃない
				if(elem.attr('name').indexOf('Rkodawari') < 0){
					if(elem.attr('name').indexOf('madori') == 0){
						val = 'on';
					}
					if(elem.attr('name').indexOf('campaign') < 0){
						$.each(items, function(i, item){							
							if (item != undefined && item.name == elem.attr("name")) items.splice(i, 1);
						});
					}
					
					items.push({name:elem.attr("name"), value:val});
					
				}			
				else {//よく利用こだわりじゃない
					var vals = val.split('|');
					for(var i = 0 ; i < vals.length ; i++){
						var kodas = vals[i].split('-');
						
						//存在するばあい→Remove
						$.each(items, function(i, item){							
							if (item != undefined && item.name == kodas[0]) items.splice(i, 1);
						});
						
						items.push({name:kodas[0], value:kodas[1]});
					}
					
					items.push({name:elem.attr("name"), value:'on'});
				}
			}
		});
				
		
		//間取り
		var madoriArray = ['10', '11', '12', '14', '21', '22', '24', '31', '32', '34', '41', '42', '44', '51'];
		var madori1 = $('#madori1').val();						
		var madori2 = $('#madori2').val();
		
		var start = '- 1';
		if(madori1 != '') start = madori1.replace('madori', '');			
		var end = '- 1';
		if(madori2 != '') end = madori2.replace('madori', '');
		
		if(start != '- 1' && end != '- 1' && parseInt(start) <= parseInt(end)){
			var startIndex = madoriArray.indexOf(start);
			var endIndex = madoriArray.indexOf(end);
			for(var index = startIndex; index <= endIndex; index++){
				items.push({name:'madori' + madoriArray[index], value:'on'});
			}
		}
		else if(start != '- 1' && end == '- 1'){
			var startIndex = madoriArray.indexOf(start);
			for(var index = startIndex; index < madoriArray.length; index++){
				items.push({name:'madori' + madoriArray[index], value:'on'});
			}
		}
		else if(start == '- 1' && end != '- 1'){
			var endIndex = madoriArray.indexOf(end);
			for(var index = 0; index <= endIndex; index++){
				items.push({name:'madori' + madoriArray[index], value:'on'});
			}
		}
		//間取り
		
		
		
		return items;
	}

	function go(page) {
		var items=prepareParams();

		items.push({name:'page',value:page||1});
		//console.dir(items);
		
		//検索するときTemp条件保存
		saveTempCondition();
		//console.dir(items);
		submit('/sp/rstobi/rstobi','POST',items);
	}
	ReSearch = go;
	function go2(page) {
		var items=[];
		var form = document.forms[0];
		for (var i=0; i<form.length; i++){
			if (form[i].name == "this_params[page]") {
				// skip
			} else if (form[i].name.substr(0,11) == "this_params") {
				if (form[i].name.match(/^this_params\[(.+)\]\[(.+)\]$/, "$1[$2]")) {
					items.push({name:form[i].name.replace(/^this_params\[(.+)\]\[(.+)\]$/, "$1[$2]"),value:form[i].value});
				} else if (form[i].name.match(/^this_params\[(.+)\]$/, "$1")) {
					items.push({name:form[i].name.replace(/^this_params\[(.+)\]$/, "$1"),value:form[i].value});
				}
			}
		}
		items.push({name:'page',value:page||1});
		submit('/sp/rstobi/rstobi','POST',items);
	}
	PageMove = go2;
	
	/*
	 * 地域、町変更
	 */
	function changeCity(){
		
		//市区町村変更
		$('#liChangePref a').on('click', function(){
			var items=prepareParams();
			submit('/sp/area/areachange/','POST',items);
		});
		
		//町変更
		$('#liChangeTown a').on('click', function(){
			var items=prepareParams();
			submit('/sp/area/town/','POST',items);
		});
		
		//路線変更
		$('#liChangeLine a').on('click', function(){
			var items=prepareParams();
			submit('/sp/area/linechange/','POST',items);
		});
		
		//駅変更
		$('#liChangeStation a').on('click', function(){
			var items=prepareParams();	
			submit('/sp/area/ekichange/','POST',items);
		});
	}
	
	//クッキー用の保存
	function saveTempCondition(){
		var items = [];
		var typ = $('input[name="search_type"]').attr("value");
		items.push('search_type:' + typ);
		
		$('.search_target').each(function(index){
			if($(this).attr("id") != ""){
				items.push('target_'+index + ':' + $(this).attr("id"));				
			}			
		});
		
		//町名検索
		$('li[name=search_targetChou]').each(function(index){
			items.push('targetchou_'+index + ':' + $(this).attr("id"));
		});

		$('input:checked').each(function(index){
			var elem = $(this);
			var val = elem.attr("value");
			if(elem.attr('name').indexOf('madori') == 0){
				val = 'on';
			}
			if(elem.attr("name") != ""){
				items.push(elem.attr("name") + ':' + val);								
			}			
		});

		$('select').each(function(index){
			if($(this).attr('name').indexOf('this_params') >= 0 || $(this).attr('name').indexOf('madori') >= 0) return;
			var elem = $(this);
			if(elem.attr("name") != ""){
				var val = elem.find("option:selected").attr("value");
				var name = elem.attr("name");
				items.push(elem.attr("name") + ':' + val);												
			}			
		});
		
		//名所
		var itemsName = [];
		var mainData = [];
		//地域検索
		var pref = $('.ttl_area').html();
		
		//市区町村
		//地域検索
		var typ = $('input[name="search_type"]').attr("value");		
		if(typ == 'area'){						
			//var pref = $('.ttl_arealine').html();
			
			//市区町村
			$('.search_target').each(function(){				
				var val = pref + ' ' + $(this).html();
				var city = $(this).attr('id').split('-')[1];

				//町
				var childCount = $('li[id^=' + city + ']').length;
				if(childCount > 0) val += ' ';
				$('li[id^=' + city + ']').each(function(index){					
					val += $(this).html();
					if(index < childCount - 1){
						val += '、';
					}
				})
				
				mainData.push(val);
			}) ;
		}
		//路線検索
		else if(typ == 'line'){
			var prefName = $('#liPrefName').val();
			var pref = $('.search_target').first().attr('id').split('-')[0];
			$('.hope_area_select').each(function(){				
				
				var val = prefName + '　' + $(this).find('.icon').html();
				var length = $(this).find('.search_target').length;
				if(length > 0) val += ' ';
				$(this).find('.search_target').each(function(index){
					val += $(this).html();
					if(index < length - 1){
						val += '、';
					}
				})
				mainData.push(val);
			});
		}
		//ショップ検索
		else if(typ == 'shop'){
			mainData.push(pref);
		}	
		
		//メインデータ
		itemsName.push({mainData: mainData});
		
		//賃料
		var tinryo = '';
		var index1 = $('select[name=tinryo1]').find('option:selected').index();
		var index2 = $('select[name=tinryo2]').find('option:selected').index();
		var length = $('select[name=tinryo2] option').length;
		if(index1 > 0 && index2 < length - 1){
			tinryo = $('select[name=tinryo1]').find('option:selected').text() + '～' + $('select[name=tinryo2]').find('option:selected').text();			
		}
		else if(index1 > 0) tinryo = $('select[name=tinryo1]').find('option:selected').text() + '～';
		else if(index2 < length - 1) tinryo = '～' + $('select[name=tinryo2]').find('option:selected').text();
		
		var vals = [];
		if($('#tinryo_jouken2').prop('checked')) vals.push('管理費・共益費含む');
		if($('#tyusyajyo_komi').prop('checked')) vals.push('駐車場代含む');
		if($('#shikikin_nashi').prop('checked')) vals.push('敷金ゼロ');
		if($('#reikin_nashi').prop('checked')) vals.push('礼金ゼロ');
		if($('#freerent').prop('checked')) vals.push('フリーレント');
		if($('#heyawari').prop('checked')) vals.push('部屋割');
		if(vals.length > 0){
			if(tinryo != '') tinryo += '（' + vals.join('、') + '）';
			else tinryo = vals.join('、');
		}			
		
		itemsName.push({tinryo:tinryo});
		//賃料		
		
		//間取り
		var madoriVal = ['10','11','12','14','21','22','24','31','32','34','41','42','44','51'];
		var madoriJP = ['ワンルーム','1K','1DK','1LDK','2K','2DK','2LDK','3K','3DK','3LDK','4K','4DK','4LDK','5K以上'];
		
		var madori1 = $('select[name=madori1]').val().replace('madori', '');
		var madori2 = $('select[name=madori2]').val().replace('madori', '');
		if( (madori1 != undefined && madori1 != '') || (madori2 != undefined && madori2 != '')){
			
			var index1 = madoriVal.indexOf(madori1);
			var index2 = madoriVal.indexOf(madori2);
			if(index1 < 0) index1 = 0;
			if(index2 < 0) index2 = madoriVal.length;
			
			var madJp = [];
			for(var i = index1; i <= index2 ; i++){
				items.push('madori' + madoriVal[i] + ':on');
				madJp.push(madoriJP[i]);
			}
			itemsName.push({madori:madJp.join('、')});
		}		
		else {
			itemsName.push({madori:''});
		}		
		//間取り
		
		//面積
		var senyu = '';
		var tinryoIndex1 = $('select[name=senyu1]').find('option:selected').index();
		var tinryoIndex2 = $('select[name=senyu2]').find('option:selected').index();
		var length = $('select[name=senyu2] option').length;
		if(tinryoIndex1 > 0 && tinryoIndex2 < length - 1){
			senyu = $('select[name=senyu1]').find('option:selected').text() + '～' + $('select[name=senyu2]').find('option:selected').text();;			
		}
		else if(tinryoIndex1 > 0) senyu = $('select[name=senyu1]').find('option:selected').text() + '～';
		else if(tinryoIndex2 < length - 1) senyu = '～' + $('select[name=senyu2]').find('option:selected').text();;
		
		itemsName.push({senyu:senyu});
		//面積
		
		//物件種別
		var syubetsu = [];
		$('input[type=checkbox][name^=syubetu]:checked').each(function(){
			var name = $(this).attr('name');
			if(name == 'syubetu1') syubetsu.push('賃貸アパート');
			else if(name == 'syubetu2') syubetsu.push('賃貸マンション');
			else if(name == 'syubetu3') syubetsu.push('戸建て・テラスハウス');
			else if(name == 'syubetu4') syubetsu.push('貸店舗・賃貸事務所');
			else if(name == 'syubetu5') syubetsu.push('駐車場');
		});
		itemsName.push({syubetu:syubetsu.join('、')});
		//物件種別
		
		//築年数
		var build = '';
		if($('select[name=built]').find('option:selected').index() > 0){
			build = $('select[name=built]').find('option:selected').text();
		}
		itemsName.push({build:build});
		//築年数
		
		//駅徒歩
		var ekitoho = '';
		if($('select[name=ekitoho]').find('option:selected').index() > 0){
			ekitoho = $('select[name=ekitoho]').find('option:selected').text();
			if($('#bas_riyou').prop('checked')) ekitoho += '（バス利用可）';				
		}
		itemsName.push({ekitoho:ekitoho});
		//駅徒歩
		
		//その他
		var other = [];
		$('input[type=checkbox][name^=kodawari]:checked').each(function(){
			var div = $(this).parent().first();						
			if(div.prop('tagName').toUpperCase() != 'SPAN') return;			
			var label = div.parent().first();
			other.push(label.text());
			
			/*
			var text = label.contents().filter(function() { 
				return this.nodeType == 3;				    
			}); 
			if(text != undefined){
				other.push(text[text.length - 1].data);
			}
			*/			
		});
		$('input[type=checkbox][name^=campaign]:checked').each(function(){
			var div = $(this).parent().first();
			if(div.prop('tagName').toUpperCase() != 'SPAN') return;	
			var label = div.parent().first();
			other.push(label.text());
		});
		itemsName.push({other:other.join('/')});
		//その他		
		
		//保存タイム
		var d = new Date();
		var date = d.getDate();
		var month = d.getMonth() + 1;
		var hour = d.getHours();
		var minute = d.getMinutes();
		var savetime = (month < 10 ? '0' : '') + String(month) + '/' + (date < 10 ? '0' : '') + String(date) + ' ' +
					   (hour < 10 ? '0' : '') + String(hour) + ':' + (minute < 10 ? '0' : '') + String(minute);
		itemsName.push({savetime:savetime});
				
		CONS.addTempCondition(JSON.stringify(items), JSON.stringify(itemsName));
		//console.dir(JSON.stringify(items));
		//console.dir(JSON.stringify(itemsName));
	}
	
	/* 実行
	----------------------------------- */
	$(function() {
		init();
		hopeAreaSelect();
		hopeStationOpen();
		clearBtn();
		selectTinryo();
		selectMadori();
		selectMenseki();
		changeCity();
		loadMadori();
	});

})(this, document);
